package com.change.service.robot;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.change.core.constant.RobotConstants;
import com.change.core.page.Page;
import com.change.dto.req.QueryRobotReq;
import com.change.dto.req.SaveRobotReq;
import com.change.dto.resp.QueryRobotResp;
import com.change.entity.robot.Robot;
import com.change.exception.BizException;
import com.change.exception.ResultStatus;
import com.change.mapper.robot.RobotMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author 坏孩子是你啊
 * @date 2022-08-18
 */
@Slf4j
@Service
public class RobotService extends ServiceImpl<RobotMapper, Robot> {
    private final RobotMapper robotMapper;

    public RobotService(RobotMapper robotMapper) {
        this.robotMapper = robotMapper;
    }

    public Page<List<QueryRobotResp>> getPage(Page page, QueryRobotReq req) {
        page.offset();
        List<QueryRobotResp> records = this.robotMapper.pageRobots(page, req);
        page.setRecords(records);
        long total = this.robotMapper.pageRobotTotal(req);
        page.setTotal(total);
        return page;
    }

    public Robot detail(Integer id) {
        LambdaQueryWrapper<Robot> query = Wrappers.lambdaQuery();
        query.eq(Robot::getId, id);
        return robotMapper.selectOne(query);
    }

    @Transactional(rollbackFor = Exception.class)
    public Robot save(SaveRobotReq req) {
        Robot robot = new Robot();
        BeanUtil.copyProperties(req, robot);
        this.robotMapper.insert(robot);
        return robot;
    }

    @Transactional(rollbackFor = Exception.class)
    public Robot update(SaveRobotReq req) {
        Robot robot = this.robotMapper.selectById(req.getId());
        BeanUtil.copyProperties(req, robot);
        this.robotMapper.updateById(robot);
        return robot;
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer delete(Integer id) {
        Robot robot = this.robotMapper.selectById(id);
        if (robot.getDeleted() == 0) {
            robot.setDeleted(1);
        }
        return this.robotMapper.updateById(robot);
    }

    /**
     * 根据机器人的账号密码生成 token
     *
     * @param robotResp 机器人信息
     * @return
     */
    public String getToken(QueryRobotResp robotResp) {
        // 获取机器人信息
        LambdaQueryWrapper<Robot> query = new LambdaQueryWrapper<>();
        if (StrUtil.isBlank(robotResp.getWxAccount())) {
            query.eq(Robot::getWxAccount, robotResp.getWxAccount());
        }
        if (StrUtil.isBlank(robotResp.getPassword())) {
            query.eq(Robot::getPassword, robotResp.getPassword());
        }
        Robot robot = this.robotMapper.selectOne(query);
        if (Objects.isNull(robot)) {
            throw new BizException(ResultStatus.Common.NOT_FOUNT_ROBOT);
        }

        Map<String, Object> payload = new HashMap<>();
        LocalDateTime now = LocalDateTime.now();
        // 签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        // 过期时间 7 天
        payload.put(JWTPayload.EXPIRES_AT, now.plusDays(7));
        // 生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        // 机器人名称
        payload.put("name", robot.getName());
        // 微信账户
        payload.put("wxAccount", robot.getWxAccount());
        // 密码
        payload.put("password", robot.getPassword());
        // 创建 token
        String token = JWTUtil.createToken(payload, RobotConstants.JWT_KEY.getBytes());

        return token;
    }
}
